<?php
namespace Sys\Controller;
use Todo\Controller\ApiController;
use Todo\Service\MessageService;

class MessageController extends ApiController {

    protected function _loadModel()
    {
        if(!$this->_model) $this->_model = D('Todo/Msg/Read');
    }

    /**
     * 消息内容
     */
    public function content(){
        $id = I('get.id');
        if(!$id) $this->apiError('参数不完整');

        $data = D('Todo/Msg/Content')->keyFind($id);
        if(!$data) $this->apiError('消息不存在');

        $this->apiData($data);
    }

    /**
     * 查看消息
     */
    public function view(){
        $id = I('get.id');
        if(!$id) $this->error('参数不完整');

        $info = D('Todo/Msg/Read')->keyFind($id);
        if(!$info) $this->error('参数不完整');

        if($info['is_read'] !== '1') {
            $info['is_read'] = '1';
            $info['read_time'] = date('Y-m-d H:i:s');
            D('Todo/Msg/Read')->save($info);
        }

        $data = D('Todo/Msg/Content')->keyFind($info['content_id']);
        if(!$data) $this->error('消息不存在');

        $this->assign('data', $data);
        $this->display();
    }

    /**
     * 标记已读
     */
    public function read(){
        $id = I('get.id');
        if(!$id) $this->error('参数不完整');

        $info = D('Todo/Msg/Read')->keyFind($id);
        if(!$info) $this->error('参数不完整');

        if($info['is_read'] !== '1') {
            $info['is_read'] = '1';
            $info['read_time'] = date('Y-m-d H:i:s');
            D('Todo/Msg/Read')->save($info);
        }
        if(I('get.info/s') == '1'){
            $this->apiData(D('Todo/Msg/Content')->keyFind($info['content_id']));
        }else{
            $this->apiSuccess();
        }
    }

    /**
     * 消息数
     */
    public function count(){
        die(MessageService::getInstance()->getMessageCount($this->_user['id'], '2'));
    }

    /**
     * 导航中的消息栏
     */
    public function nav(){
        $total = MessageService::getInstance()->getMessageCount($this->_user['id'], '2');
        $this->assign('total', $total);
        $this->display();
    }
}